home *** CD-ROM | disk | FTP | other *** search
/ C/C++ Users Group Library 1996 July / C-C++ Users Group Library July 1996.iso / vol_200 / 264_01 / chmod.c < prev    next >
Text File  |  1980-01-01  |  2KB  |  104 lines

  1. /*
  2.  * chmod - change file modes
  3.  * Usage: chmod +|-ahrs file...
  4.  *
  5.  * Attributes that can be added (+) or removed (-):
  6.  * a    archive
  7.  * h    hidden
  8.  * r    read only
  9.  * s    system
  10.  *
  11.  * This program is in the public domain.
  12.  * David MacKenzie
  13.  * 6522 Elgin Lane
  14.  * Bethesda, MD 20817
  15.  *
  16.  * Latest revision: 05/08/88
  17.  */
  18.  
  19. #include <stdio.h>
  20. #include <stat.h>
  21.  
  22. _main(argc, argv)
  23.     int     argc;
  24.     char  **argv;
  25. {
  26.     int     optind;        /* Index into argv. */
  27.     int     errs = 0;        /* # of files couldn't chmod. */
  28.     int     mask;        /* Modes to change. */
  29.  
  30.     if (argc < 3)
  31.     usage();
  32.  
  33.     mask = parseattr(argv[1]);
  34.  
  35.     for (optind = 2; optind < argc; ++optind)
  36.     errs += chmodfile(argv[optind], mask, *argv[1]);
  37.  
  38.     exit(errs);
  39. }
  40.  
  41. /*
  42.  * Perform the operation on the modes of the file.
  43.  * Return 0 if ok, 1 if error.
  44.  */
  45. chmodfile(file, mode, op)
  46.     char   *file;
  47.     int     mode;        /* Mode(s) to change in stat format. */
  48.     char    op;            /* Operation, + or -. */
  49. {
  50.     struct stat sbuf;
  51.  
  52.     if (stat(file, &sbuf) == -1) {
  53.     fprintf(stderr, "%s: File not found\n", file);
  54.     return 1;
  55.     }
  56.     if (op == '+')
  57.     sbuf.st_attr |= mode;
  58.     else
  59.     sbuf.st_attr &= ~mode;
  60.     if (chmod(file, sbuf.st_attr) == -1) {
  61.     perror(file);
  62.     return 1;
  63.     }
  64.     return 0;
  65. }
  66.  
  67. /*
  68.  * Return a stat-compatible mask for the attributes specified in the
  69.  * string.  Also, exit if the string is not a valid attribute specifier.
  70. */
  71. parseattr(s)
  72.     char   *s;
  73. {
  74.     int     mask = 0;
  75.  
  76.     if (s[0] != '+' && s[0] != '-' || s[1] == 0)
  77.     usage();
  78.  
  79.     for (++s; *s; ++s)
  80.     switch (*s) {
  81.     case 'r':
  82.         mask |= ST_RDONLY;
  83.         break;
  84.     case 'h':
  85.         mask |= ST_HIDDEN;
  86.         break;
  87.     case 's':
  88.         mask |= ST_SYSTEM;
  89.         break;
  90.     case 'a':
  91.         mask |= ST_ARCHIV;
  92.         break;
  93.     default:
  94.         usage();
  95.     }
  96.     return mask;
  97. }
  98.  
  99. usage()
  100. {
  101.     fprintf(stderr, "Usage: chmod +|-ahrs file...\n");
  102.     exit(1);
  103. }
  104.